package com.beemans.corekit.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.text.format.Formatter;
import android.util.Log;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.beemans.corekit.databinding.ActivityMainBinding;
import com.beemans.corekit.duplicate.AndroidDuplicateScanner;
import com.beemans.corekit.duplicate.ScanListener;
import com.beemans.corekit.helper.NotificationHelper;
import com.beemans.corekit.integration.toolkit.ToastUtils;
import com.beemans.corekit.utils.PermissionUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity<ActivityMainBinding> {

    @Nullable
    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initViews() {
    }

    @Override
    protected void initEvents() {
        getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
            }
        });

        //noinspection CodeBlock2Expr
        binding.mainBtnToast.setOnClickListener(v -> {
            ToastUtils.showShort("Action completed successfully!");
        });

        binding.mainBtnAdmob.setOnClickListener(v -> {
            final Intent intent = new Intent(this, AdmobActivity.class);
            startActivity(intent);
        });

        binding.mainBtnTopOn.setOnClickListener(v -> {
            final Intent intent = new Intent(this, TopOnActivity.class);
            startActivity(intent);
        });

        //noinspection CodeBlock2Expr
        binding.mainBtnLocalPush.setOnClickListener(v -> {
            PermissionUtils.requestNotificationPermission(aBoolean -> {
                if (aBoolean) {
                    NotificationHelper.getInstance().showLocalNotification(MainActivity.this);
                }
            });
        });

        //noinspection CodeBlock2Expr
        binding.mainBtnRemotePush.setOnClickListener(v -> {
            PermissionUtils.requestNotificationPermission(aBoolean -> {
                if (aBoolean) {
                    final Map<String, String> customData = new HashMap<>();
                    customData.put("push_date", "");
                    customData.put("push_id", "0");
                    customData.put("title", "3431434314343143431434314343143431434314343143431434314343143431434314343143431434314");
                    customData.put("body", "33333333333333333333333333333333333333333333333333333333333333333333333333333333333333");
                    customData.put("img_url", "https://widget007.oss-cn-beijing.aliyuncs.com/gp_push/2025-09-02/cb12d13c0ffd1fe76f6bec1d597ea1ce.png");
                    customData.put("btn_link", "4444");
                    customData.put("btn_text", "view");
                    customData.put("btn_type", "3");

                    NotificationHelper.getInstance().showRemoteNotification(MainActivity.this, customData);
                }
            });
        });

        binding.mainBtnScanDuplicateFile.setOnClickListener(v -> startDuplicateScan());
    }

    private void startDuplicateScan() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            return;
        }

        PermissionUtils.requestAllFileAccessPermission(isGranted -> {
            if (!isGranted) {
                return;
            }

            new AndroidDuplicateScanner().startScan(Environment.getExternalStorageDirectory(), new ScanListener() {
                @Override
                public void onScanProgress(int scannedFiles, int potentialDuplicates) {
//                    Log.e("susu", "onScanProgress --- scannedFiles:" + scannedFiles + "   potentialDuplicates:" + potentialDuplicates);
                }

                @Override
                public void onDuplicateFound(@NonNull List<File> duplicateGroup) {
//                    Log.e("susu", "onDuplicateFound --- duplicateGroup:" + duplicateGroup);
                }

                @Override
                public void onScanCompleted(@NonNull List<List<File>> allDuplicates) {
                    Log.e("susu", "========== 扫描完成 ==========");
                    Log.e("susu", "发现 " + allDuplicates.size() + " 组重复文件");
                    Log.e("susu", "==============================");

                    // 统计数据
                    int totalDuplicateFiles = 0;  // 重复文件总数
                    long totalDuplicateSize = 0;   // 重复文件总大小
                    long wastedSpace = 0;          // 可释放空间（保留每组中1个文件，其他都是浪费的）

                    int groupIndex = 1;
                    for (List<File> duplicateGroup : allDuplicates) {
                        Log.e("susu", "");
                        Log.e("susu", "【重复组 " + groupIndex + "】共 " + duplicateGroup.size() + " 个文件：");

                        // 计算这组的大小（假设所有文件大小相同，取第一个）
                        long groupFileSize = duplicateGroup.isEmpty() ? 0 : duplicateGroup.get(0).length();
                        totalDuplicateSize += groupFileSize * duplicateGroup.size();
                        totalDuplicateFiles += duplicateGroup.size();
                        // 可释放空间 = 文件大小 × (数量 - 1)，因为需要保留一个
                        wastedSpace += groupFileSize * (duplicateGroup.size() - 1);

                        int fileIndex = 1;
                        for (File file : duplicateGroup) {
                            Log.e("susu", "  文件 " + fileIndex + ":");
                            Log.e("susu", "    名称: " + file.getName());
                            Log.e("susu", "    路径: " + file.getAbsolutePath());
                            Log.e("susu", "    大小: " + Formatter.formatFileSize(MainActivity.this, file.length()));
                            Log.e("susu", "    修改时间: " + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(new java.util.Date(file.lastModified())));
                            fileIndex++;
                        }

                        groupIndex++;
                    }

                    // 输出统计信息
                    Log.e("susu", "");
                    Log.e("susu", "========== 统计信息 ==========");
                    Log.e("susu", "重复文件组数: " + allDuplicates.size() + " 组");
                    Log.e("susu", "重复文件总数: " + totalDuplicateFiles + " 个");
                    Log.e("susu", "重复文件占用空间: " + Formatter.formatFileSize(MainActivity.this, totalDuplicateSize));
                    Log.e("susu", "可释放空间: " + Formatter.formatFileSize(MainActivity.this, wastedSpace) + " (删除重复文件后)");
                    Log.e("susu", "==============================");
                    Log.e("susu", "");
                    Log.e("susu", "========== 扫描结束 ==========");
                }

                @Override
                public void onScanError(@NonNull String error) {
                    Log.e("susu", "onScanError --- error:" + error);
                }
            });
        });
    }
}